package com.mrd.gtimp.business.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.entity.BaseAttachment;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.DeclarationAttachment;
import com.mrd.gtimp.business.entity.DeclarationOffer;
import com.mrd.gtimp.business.entity.DiDanAttachment;
import com.mrd.gtimp.business.entity.FundAjustment;
import com.mrd.gtimp.business.entity.RegisteredCompany;
import com.mrd.gtimp.business.entity.RegisteredCompanyAttachment;
import com.mrd.gtimp.business.repository.AttachmentDao;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.UploadFileUtil;

import org.apache.commons.lang3.StringUtils;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Service
public class AttachmentBiz extends BaseBiz<Attachment> {
	@Resource
	private RegisteredCompanyAttachmentBiz	registeredCompanyAttachmentBiz;
	@Resource
	private DeclarationAttachmentBiz		declarationAttachmentBiz;
	@Resource
	private DiDanAttachmentBiz				diDanAttachmentBiz;
	@Resource
	private FundAjustmentBiz				fundAjustmentBiz;
	@Resource
	private BaseAttachmentBiz				baseAttachmentBiz;
	@Resource
	private DeclarationOfferBiz				declarationOfferBiz;
	@Resource
	private AttachmentDao					attachmentDao;
	/*
	 * (non-Javadoc)
	 * @see com.mrd.gtimp.business.biz.AttachmentBiz#cancleUploadFile(java.lang.String)
	 */

	public boolean cancleUploadFile(String id,String businessType) {
		try {
			Attachment soFile = findEntityById(id);
			// 更新数据库
			String sql = "delete from T_BIZ_ATTACHMENT where id=:id";
			String updateSql = "";
			if("T".equals(businessType)) {
				updateSql = "update t_biz_trail t set t.SO_FILE_ID = '' where t.SO_FILE_ID=:id";
			} else if("D".equals(businessType)) {
				updateSql = "update t_biz_declaration t set t.containerinfo_file_id = '' where t.containerinfo_file_id=:id";
			}
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("id", id);
			excuteSql(sql, parameters);
			excuteSql(updateSql, parameters);
			// 删除文件
			String path = UploadFileUtil.getFilePath();
			File file = new File(path + soFile.getPath());
			file.delete();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 查询对应tyope, 和bid的附件
	 * @param type
	 *            附件类型
	 * @param bid
	 *            业务ID
	 * @return 附件集合
	 */
	public List<Object> queryBaseAttachmentOrAttachment(String type,String bid) {
		List<Object> attas = new ArrayList<>();
		if("register".equals(type)) {
			RegisteredCompany registeredCompany = new RegisteredCompany();
			registeredCompany.setReg_company_id(bid);
			List<RegisteredCompanyAttachment> reAttas = registeredCompanyAttachmentBiz
			        .findByRegisteredCompany(registeredCompany);
			attas.addAll(reAttas);
		} else if("declaration".equals(type)) {
			Declaration declaration = new Declaration();
			declaration.setId(bid);
			List<DeclarationAttachment> declaAttas = declarationAttachmentBiz
			        .findByDeclaration(declaration);
			attas.addAll(declaAttas);
		} else if("didan".equals(type)) {
			Declaration declaration = new Declaration();
			declaration.setId(bid);
			List<DiDanAttachment> didanAttas = diDanAttachmentBiz.findByDeclaration(declaration);
			attas.addAll(didanAttas);
		} else if("pay".equals(type)) {
			try {
				FundAjustment fundAjustment = fundAjustmentBiz.findEntityById(bid);
				attas.add(fundAjustment.getTransferCertificate());
			} catch (QueryException e) {
				e.printStackTrace();
			}
		} else if("declaOffer".equals(type)) {
			try {
				DeclarationOffer offer = declarationOfferBiz.findEntityById(bid);
				attas.add(offer.getUpload_id());
			} catch (QueryException e) {
				e.printStackTrace();
			}
		}
		return attas;
	}

	/**
	 * 查询对应tyope, 和bid的附件
	 * @param type
	 *            附件类型
	 * @param aid
	 *            附件ID
	 * @return 附件集合
	 */
	public Object querySingleBaseAttachmentOrAttachment(String type,String aid) {
		Object a = null;
		try {
			if("reg".equals(type) || "register".equals(type) || "declaration".equals(type)
			        || "didan".equals(type)) {
				a = baseAttachmentBiz.findEntityById(aid);
			} else if("pay".equals(type) || "declaOffer".equals(type)) {
				a = this.findEntityById(aid);
			}
		} catch (QueryException e) {
			e.printStackTrace();
		}
		return a;
	}

	@Resource
	// 该处指定注入BaseRepository的dao对象
	@Qualifier("attachmentDao")
	public void setBaseRepository(BaseRepository<Attachment, String> baseRepository) {
		super.baseRepository = baseRepository;
	}

	/**
	 * 删除附件
	 * @param ids
	 */
	@Transactional
	public void deleteAttachement(String type,String... ids) {
		if(StringUtils.isNotEmpty(type) && type.equalsIgnoreCase("declaOffer")){
			this.deleteOfferAttachement(ids);
		}else{
			List<BaseAttachment> attachments = baseAttachmentBiz.findByIds(ids);
			List<File> files = attachments.size() == 1
					? Collections.singletonList(new File(attachments.get(0).getPath()))
					: Collections.emptyList();
			files.forEach(File::deleteOnExit);
			baseAttachmentBiz.deleteInBatch(attachments);
		}
	}

	/**
	 * 专用于供应商报价的附件删除
	 * @param ids
     */
	@Transactional
	public void deleteOfferAttachement(String... ids){
		List<Attachment> attachments = this.findByIds(ids);
		List<File> files = attachments.size() == 1
				? Collections.singletonList(new File(attachments.get(0).getPath()))
				: Collections.emptyList();
		files.forEach(File::deleteOnExit);
		this.baseRepository.deleteInBatch(attachments);
	}

	/**
	 * 专用于供应商报价的附件删除
	 */
	@Transactional
	public void deleteOfferAttachementByBillNos(String... billNos){
		List<Attachment> attachments = attachmentDao.findByBillNos(Arrays.asList(billNos));
		if(CollectionUtils.isEmpty(attachments)){
			return;
		}
		List<File> files = attachments.size() == 1
				? Collections.singletonList(new File(attachments.get(0).getPath()))
				: Collections.emptyList();
		files.forEach(File::deleteOnExit);
		this.baseRepository.deleteInBatch(attachments);
	}


	/**
	 * 根据ID进行查询
	 * @param ids
	 *            Array|String
	 */
	public List<Attachment> findByIds(String... ids) {
		return baseRepository.findAll(Arrays.asList(ids));
	}

	/**
	 * 根据ID进行查询
	 * @param nos
	 *            List
	 */
	public List<Attachment> findByBillNos(List<String> nos) {
		return attachmentDao.findIdAndNameAndBillNoByBillNos(nos);
	}
}
